package com.nuliji.help;

import com.nuliji.constants.SessionKey;
import com.nuliji.dto.SmsSessionDto;
import com.nuliji.dto.response.UploadInfoDto;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.third.aliyuncs.Aliyun;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

import static com.nuliji.tools.Tools.encodeBase64;
import static com.nuliji.tools.Tools.getHmacSha1;

/**
 * Created by GaoJie on 2017/11/3.
 */
@Service
public class UploadHelp {
    private static final Logger logger = LoggerFactory.getLogger(UploadHelp.class);
    private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static String format = "{\"expiration\":\"%s\",\"conditions\":[[\"content-length-range\",0,%d],[\"starts-with\",\"$key\",\"%s\"]]}";

    final public String UPLOAD_IMAGE = "nuliji-edu-all-files.oss-cn-beijing.aliyuncs.com";
    final public String UPLOAD_FILE = "nuliji-edu-all-image.oss-cn-beijing.aliyuncs.com";

    public UploadInfoDto authorize(String type, String module, int size){
        if(!type.equals(UPLOAD_FILE) && !type.equals(UPLOAD_IMAGE))
            throw new ParameterException("上传文件类型错误");
        UploadInfoDto dto = new UploadInfoDto();
        dto.setHost("https://"+type);
        dto.setOSSAccessKeyId(Aliyun.accessKeyId);
        dto.setSuccess_action_status("200");

        ZonedDateTime ldt = ZonedDateTime.now();
        dto.setKey(module + "/" + ldt.format(dtf) + "/" + UUID.randomUUID().toString());
        String policy = String.format(format,
                ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")),
                size,
                dto.getKey()
        );
        dto.setPolicy(encodeBase64(policy));
        dto.setSignature(encodeBase64(getHmacSha1(encodeBase64(policy), Aliyun.accessKeySecret)));
        logger.debug("{}", dto);
        return dto;
    }

    public boolean key(String mobile, String code, HttpSession session) {
        SmsSessionDto dto = (SmsSessionDto) session.getAttribute(SessionKey.SMS_KEY);
        if(dto == null){
            throw new ParameterException("手机验证码错误！");
        }
        session.removeAttribute(SessionKey.SMS_KEY);
        String originCode = dto.getCode();
        String originMobile = dto.getSendMobile();
        Date expireTime = dto.getExpireTime();
        if (StringUtils.equalsIgnoreCase(originCode, code) && StringUtils.equalsIgnoreCase(originMobile, mobile)) {
            if (new Date().getTime() > expireTime.getTime()) {
                throw new ParameterException("验证码已过期！");
            }
            return true;
        }
        return false;
    }
}
